package org.papiez.appengine.hello.world;

import static com.sun.jersey.api.core.ResourceConfig.FEATURE_DISABLE_WADL;
import static com.sun.jersey.spi.container.servlet.ServletContainer.FEATURE_FILTER_FORWARD_ON_404;

import java.util.Collections;
import java.util.HashMap;
import java.util.Map;

import javax.inject.Singleton;

import org.codehaus.jackson.jaxrs.JacksonJaxbJsonProvider;

import com.google.inject.Guice;
import com.google.inject.Injector;
import com.google.inject.servlet.GuiceServletContextListener;
import com.sun.jersey.guice.JerseyServletModule;
import com.sun.jersey.guice.spi.container.servlet.GuiceContainer;

public final class ContainerConfigurator extends GuiceServletContextListener {
	private static final String EVERYTHING = "/*";

	private static final Map<String, String> GUICE_CONTAINER_CONFIGURATION;

	static {
		Map<String, String> map = new HashMap<String, String>();

		map.put(FEATURE_FILTER_FORWARD_ON_404, Boolean.toString(true));
		map.put(FEATURE_DISABLE_WADL, Boolean.toString(true));

		GUICE_CONTAINER_CONFIGURATION = Collections.unmodifiableMap(map);
	}

	@Override
	protected Injector getInjector() {
		return Guice.createInjector(new ApplicationModule(),
				new ContainerModule());
	}

	private static class ContainerModule extends JerseyServletModule {
		@Override
		protected void configureServlets() {
			// Enable JSON marshalling/unmarshalling
			bind(JacksonJaxbJsonProvider.class).in(Singleton.class);

			filter(EVERYTHING).through(GuiceContainer.class,
					GUICE_CONTAINER_CONFIGURATION);

			// Fallback to the servlet
			serve(EVERYTHING).with(HelloWorldServlet.class);
		}
	}
}
